package jp.co.menox.controller.tmserver.borrow;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import jp.co.menox.controller.tmserver.TmServerControllerBase;
import jp.co.menox.tmcommon.model.Lending;
import jp.co.menox.tmserver.searchform.bollow.LendingSearchForm;
import jp.co.menox.tmserver.service.CategoryService;
import jp.co.menox.tmserver.service.LendingHistoryService;
import jp.co.menox.tmserver.service.LendingService;

import org.slim3.controller.Navigation;
import org.slim3.util.BeanUtil;

/**
 * 借りたいものを探す・予約する画面
 * @author
 *
 */
public class LendingSearchController extends TmServerControllerBase {

    protected LendingService service;
    protected CategoryService categoryService;
    protected LendingHistoryService historyService;
    {
        service = new LendingService();
        categoryService = new CategoryService();
        historyService = new LendingHistoryService();
    }

    @Override
    public Navigation run() throws Exception {
        // 検索条件
        LendingSearchForm searchForm = new LendingSearchForm();
        BeanUtil.copy(request, searchForm);
        
        // 表示用リストを取得する
        List<Lending> modelList;
        List<Boolean> reserveList;
        String command = this.asString("command");
        if (command == null || !command.equals("search")) {
            // 初期呼び出し／検索ではない：　初期表示では空リスト
            modelList = Collections.<Lending>emptyList();
            reserveList = Collections.<Boolean>emptyList();
        } else {
            // 検索：表示対象行範囲の切り出し
            modelList = service.getLendingListWithSearchingCondition(searchForm);
            reserveList = historyService.getCanReserve(modelList);
        }
        
        // 表示用mapの取得
        Map<Long, String> categoryMap = categoryService.getCategoryMap();
        Map<Long, String> userMap = userService.getUserMap();
        
        // 表示用変数設定
        requestScope("lendingList", modelList);
        requestScope("reserveList", reserveList);
        requestScope("cateMap", categoryMap);
        requestScope("userMap", userMap);
        requestScope("searchForm", searchForm);
        return forward("lendingSearch.jsp");
        
    }
}
